package com.sea.physical.controller;


import com.alibaba.excel.EasyExcel;
import com.alibaba.excel.util.StringUtils;
import com.alibaba.excel.write.style.column.LongestMatchColumnWidthStyleStrategy;
import com.codecrane.core.util.DateUtils;
import com.codecrane.core.util.ExcelUtil;
import com.codecrane.core.web.AjaxReturn;
import com.sea.physical.entity.*;
import com.sea.physical.service.*;
import com.codecrane.core.web.Ajax;
import com.codecrane.core.web.AjaxTableReturn;
import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import com.sea.physical.service.impl.CreateDespatchPlanServiceImpl;
import com.sea.product.service.ChannelService;
import com.sea.supply.entity.Buy;
import com.sea.supply.service.SupplierService;
import org.apache.poi.hssf.usermodel.HSSFWorkbook;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.io.OutputStream;
import java.io.UnsupportedEncodingException;
import java.net.URLEncoder;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Date;
import java.util.List;

/**
 * 发运
 * @author 陈鸿飞
 */
@Controller
@RequestMapping(value = "/sea/physical/despatch")
public class CreateDespatchController {

    @Autowired
    private CreateDespatchPlanService createDespatchPlanService;
    @Autowired
    private CreateDespatchSkuService createDespatchSkuService;
    @Autowired
    private CreateDistributePlanService createDistributePlanService;
    @Autowired
    private PortService portService;
    @Autowired
    private CreatePlanService createPlanService;
    @Autowired
    private RecordService recordService;
    @Autowired
    private SupplierService supplierService;
    @Autowired
    private CreateDespatchPlanServiceImpl createDespatchPlanServiceImpl;
    @Autowired
    private ChannelService channelService;

    /**
     * 管理主页面
     *
     * @param model
     * @return
     */
    @RequestMapping("/main")
    public String main(Model model) {
        return "/sea/physical/createDespatch/main";
    }

    @RequestMapping("/report")
    public String report(Model model) {
        //渠道
        model.addAttribute("channel", channelService.findByCnd(null));
        return "/sea/physical/createDespatch/report";
    }
    /**
     * 修改详细
     * @param model
     * @return
     */
    @RequestMapping("/editSku")
    public String editSku(Model model,@RequestParam("id")Integer id) {
        CreateDespatchSku despatch = createDespatchSkuService.findById(id);
        model.addAttribute("despatch",despatch);
        CreateDespatchPlan despatchPlan = createDespatchPlanService.findByCreateId(despatch.getCreateId());
        model.addAttribute("despatchPlan",despatchPlan);
        return "/sea/physical/createDespatch/editSku";
    }

    /**
     * 管理主页面
     *
     * @param model
     * @return
     */
    @RequestMapping("/editPage")
    public String editPage(Model model,@RequestParam("createId")Integer createId) {
        CreateDespatchPlan despatchPlan = createDespatchPlanService.findByCreateId(createId);
        model.addAttribute("createPlan",despatchPlan);
        model.addAttribute("port",portService.findByLevel(2));
        if(null != despatchPlan.getDespatchStore()){
            List<Port> list = portService.findByParenId(despatchPlan.getDespatchDest());
            model.addAttribute("ware",list);
        }else{
            model.addAttribute("ware",null);
        }
        model.addAttribute("supplier",supplierService.findByCnd( null));
        return "/sea/physical/createDespatch/edit";
    }

    /**
     * 分页条件查询
     *
     * @param pagesize
     * @param start
     * @return
     */
    @ResponseBody
    @RequestMapping("/findByCnd")
    public AjaxTableReturn findByCnd(@RequestParam(value = "limit", defaultValue = "10") int pagesize,
                                     @RequestParam(value = "offset", defaultValue = "0") int start,
                                     CreateDespatchPlan createDespatchPlan) {
        start = start > 0 ? start / pagesize + 1 : 1;
        PageHelper.startPage(start, pagesize);
        createDespatchPlan.setCreatePlanStatus(2);
        List<CreateDespatchPlan> list = createDespatchPlanService.findByCnd(createDespatchPlan);
        PageInfo<CreateDespatchPlan> page = new PageInfo<>(list);
        return Ajax.tableDataOk(page.getTotal(), page.getList());
    }
    /**
     * 分页条件查询
     *
     * @param createId
     * @return
     */
    @ResponseBody
    @RequestMapping("/findByCreateId")
    public List<CreateDespatchSku> findByCreateId(Integer createId) {
        List<CreateDespatchSku> list = createDespatchSkuService.findByCreateId(createId);
        return list;
    }

    /**
     * 保存
     * @param createDespatchPlan
     * @return
     */
    @ResponseBody
    @RequestMapping(value = "/usave", method = RequestMethod.POST)
    public AjaxReturn usave(CreateDespatchPlan createDespatchPlan) {
        AjaxReturn result = Ajax.fail().setMsg("保存失败！");
        try{
            if (null != createDespatchPlan && createDespatchPlanService.usave(createDespatchPlan) > 0) {
                createDespatchPlanService.updateTotal(createDespatchPlan.getCreateId());
                result.setOk(true).setMsg("保存成功！");
            }
        } catch (NullPointerException e){
            e.printStackTrace();
            result.setMsg("系统异常,请联系管理员!");
            return result;
        } catch (RuntimeException e){
            e.printStackTrace();
            result.setMsg(e.getMessage());
            return result;
        } catch (Exception e){
            e.printStackTrace();
            result.setMsg("系统异常,请联系管理员!");
            return result;
        }
        return result;
    }

    @ResponseBody
    @RequestMapping(value = "/change", method = RequestMethod.POST)
    @Transactional(rollbackFor = Exception.class)
    public AjaxReturn change(CreateDespatchSku createDespatchSku) {
        AjaxReturn result = Ajax.fail().setMsg("保存失败！");
        try{

            CreateDespatchPlan createDespatchPlan = createDespatchPlanService.findByCreateId(createDespatchSku.getCreateId());
            if (null != createDespatchSku && createDespatchPlanService.change(createDespatchSku) > 0) {
                createDespatchSkuService.getCreateSkuInfo(createDespatchSku);
                createDespatchPlanServiceImpl.updateSkuFreight(createDespatchPlan);
                createDespatchSkuService.usave(createDespatchSku);
                if(!createDespatchPlan.getFreightType().equals("整柜")) {
                    createDespatchPlanService.updateTotal(createDespatchSku.getCreateId());
                    createDistributePlanService.updateTotal(createDespatchSku.getCreateId());
                }
                result.setOk(true).setMsg("保存成功！");
            }
        }catch (RuntimeException e){
            e.printStackTrace();
            result.setMsg("系统异常,请联系管理员!");
            return result;
        } catch (Exception e){
            e.printStackTrace();
            result.setMsg("系统异常,请联系管理员!");
            return result;
        }
        return result;
    }



    /**
     * 保存
     * @param createPlan
     * @return
     */
    @ResponseBody
    @RequestMapping(value = "/send", method = RequestMethod.POST)
    public AjaxReturn send(CreatePlan createPlan) {
        AjaxReturn result = Ajax.fail().setMsg("发运失败！");
        try {
            //更新状态
            createPlanService.updateStatus(createPlan.getCreatePlanStatus(), createPlan.getId());
            //新增记录
            recordService.save(createPlan.getId(),3,"", DateUtils.dateToString(new Date()));
            result.setOk(true).setMsg("发运成功！");
        }catch (RuntimeException e){
            result.setMsg(e.getMessage());
        }catch (Exception e) {
            e.printStackTrace();
            result.setMsg(e.getMessage());
        }
        return result;
    }

    /**
     * 分页条件查询
     *
     * @param pagesize
     * @param start
     * @return
     */
    @ResponseBody
    @RequestMapping("/getReport")
    public AjaxTableReturn getReport(@RequestParam(value = "limit", defaultValue = "10") int pagesize,
                                     @RequestParam(value = "offset", defaultValue = "0") int start,
                                     CreateDespatchReport createDespatchReport) {
        start = start > 0 ? start / pagesize + 1 : 1;
        PageHelper.startPage(start, pagesize);
        List<CreateDespatchReport> report = createDespatchSkuService.getReport(createDespatchReport);
        PageInfo<CreateDespatchReport> page = new PageInfo<>(report);
        return Ajax.tableDataOk(page.getTotal(), page.getList());
    }


    /**
     * 导出当前数据
     * @param response
     * @param
     */
    @RequestMapping(value = "/export")
    @ResponseBody
    public void export(HttpServletRequest request, HttpServletResponse response, @RequestParam("ids") Integer ids[])
    {
        List<CreateDespatchSku> list = createDespatchSkuService.getRows(ids);
        String[] title = {
                "柜号","装柜时间","shipment ID","渠道","SKU","产品名称","颜色","尺码(CM)","尺码(INCH)","FNSKU","Listing",
                "数量","供应商","总件数","总箱数"
                ,"总毛重"
                ,"总净重","总体积",
                "PO号","含税单价","不含税单价","报关金额","报关税率","清关金额","清关税率","预估税金","备注",
                 "柜型", "运输方式", "国家", "装柜地点", "装柜时间", "实际装柜时间", "出运港", "目的港"
                ,"目的港仓库","运费","仓库","出运港","目的港","目的港仓库"};
        String fileName = "发运报表" + org.apache.http.client.utils.DateUtils.formatDate(new Date(), "yyyyMMdd") + ".xls";
        String sheetName = "发运报表";
        String[][] content = new String[list.size()][40];
        for (int i = 0; i < list.size(); i++) {
            content[i] = new String[title.length];
            CreateDespatchSku map = list.get(i);
            content[i][0] = map.getCreatePlanNo();
            content[i][1] = map.getCreatePlanPlaceDate();
            content[i][2] = map.getCreateShipmentId();
            content[i][3] = map.getCreateChannelName();
            content[i][4] = map.getCreateSku();
            content[i][5] = map.getProductName();
            content[i][6] = map.getProductColorName();
            content[i][7] = map.getProductCm();
            content[i][8] = map.getProductInch();
            content[i][9] = map.getCreateFnSku();
            content[i][10] = map.getCreateListing();

            content[i][11] = map.getCreateNumber().toString();
            content[i][12] = map.getCreateSupplierName();
            content[i][13] = map.getCreateNumberTotal().toString();
            content[i][14] = map.getCreateBoxNumber().toString();

            content[i][15] = map.getCreateWeightTotal().toString();
            content[i][16] = map.getCreateKgTotal().toString();
            content[i][17] = map.getCreateVolumeTotal().toString();
            content[i][18] = map.getErpProducePo();
            content[i][19] = map.getErpProducePrice().toString();
            content[i][20] = map.getErpProduceUnitPrice().toString();
            content[i][21] = map.getCreateMoney().toString();
            content[i][22] = map.getCreatePercent().toString();
            content[i][23] = map.getCreateCustomMoney().toString();
            content[i][24] = (map.getCreateCustomRate()*100)+"";
            content[i][25] = map.getCreateCustomTax().toString();
            content[i][26] = map.getCreateRemark()==null?"":map.getCreateRemark().toString();
            content[i][27] = map.getCreatePlanCabinetName();
            content[i][28] = map.getTransportName();
            content[i][29] = map.getCountryName();
            content[i][30] = map.getCreatePlanPlace();

            content[i][31] = map.getDespatchDate();
            content[i][32] = map.getDespatchPortName();
            content[i][33] = map.getDespatchDestName();
            content[i][34] = map.getDespatchStoreName();
            content[i][35] = map.getDespatchFreight().toString();
            content[i][36] = map.getCreateWareName();
            content[i][37] = map.getDespatchPortName();
            content[i][38] = map.getDespatchDestName();
            content[i][39] = map.getDespatchStoreName();

        }
        //创建HSSFWorkbook 艾弗森
        HSSFWorkbook wb = ExcelUtil.getHSSFWorkbook(sheetName, title, content, null);
        //响应到客户端
        try {
            this.setResponseHeader(response, fileName);
            OutputStream os = response.getOutputStream();
            wb.write(os);
            os.flush();
            os.close();
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    /**
     * 导出当前数据
     * @param response
     * @param
     */
    @RequestMapping(value = "/exportReport")
    @ResponseBody
    public void exportReport(HttpServletRequest request, HttpServletResponse response, CreateDespatchReport createDespatchReport)
    {
        List<CreateDespatchReport> list = createDespatchSkuService.getReport(createDespatchReport);
        String[] title = {
                "柜号","装柜时间","运输方式","shipment ID","渠道","SKU","产品名称","颜色","尺码","Listing",
                "计划数量","发运数量","装箱量","总箱数","总件数","供应商","PO","总毛重","总净重","总体积","柜型"
                , "运输方式", "出运港", "目的港","目的港仓库","状态","发运时间","开船时间","清关时间","送货时间","入库时间"
                };
        String fileName = "发运报表" + org.apache.http.client.utils.DateUtils.formatDate(new Date(), "yyyyMMdd") + ".xls";
        String sheetName = "发运报表";
        String[][] content = new String[list.size()][31];
        for (int i = 0; i < list.size(); i++) {
            content[i] = new String[title.length];
            CreateDespatchReport map = list.get(i);
            content[i][0] = map.getCreatePlanNo();
            content[i][1] = map.getCreatePlanPlaceDate();
            content[i][2] = map.getCreatePlanTransport();
            content[i][3] = map.getCreateShipmentId();
            content[i][4] = map.getCreateChannelName();
            content[i][5] = map.getCreateSku();
            content[i][6] = map.getProductName();
            content[i][7] = map.getProductColorName();
            content[i][8] = map.getProductSizeName();

            content[i][9] = map.getCreateListing();
            content[i][10] = map.getCreateNumber()+"";
            content[i][11] =(null==map.getCreateNewNumber()?0+"":map.getCreateNewNumber()+"") ;
            content[i][12] =(null==map.getCreatePackage()?0+"":map.getCreatePackage()+"") ;
            content[i][13] =(null==map.getCreateBoxNumber()?0+"":map.getCreateBoxNumber()+"") ;
            content[i][14] =(null==map.getCreateNumberTotal()?0+"":map.getCreateNumberTotal()+"") ;
            content[i][15] =(null==map.getCreateSupplierName()?"":map.getCreateSupplierName()+"") ;
            content[i][16] =(null==map.getErpProducePo()?"":map.getErpProducePo()+"") ;
            content[i][17] =(null==map.getCreateWeightTotal()?0+"":map.getCreateWeightTotal()+"") ;
            content[i][18] =(null==map.getCreateKgTotal()?0+"":map.getCreateKgTotal()+"") ;
            content[i][19] =(null==map.getCreateVolumeTotal()?0+"":map.getCreateVolumeTotal()+"") ;
            content[i][20] = map.getCreatePlanCabinetName();
            content[i][21] = map.getCreatePlanTransport();
            content[i][22] = map.getDespatchPortName();
            content[i][23] = map.getDespatchDestName();
            content[i][24] = map.getDespatchStoreName();
            content[i][25] = map.getCreatePlanStatus();
            content[i][26] = (null==map.getBoatDate()?"":map.getBoatDate()+"") ;
            content[i][27] = (null==map.getDriveBoatDate()?"":map.getDriveBoatDate()+"") ;
            content[i][28] = (null==map.getClearDate()?"":map.getClearDate()+"") ;
            content[i][29] = (null==map.getSendDate()?"":map.getSendDate()+"") ;
            content[i][30] = (null==map.getStockDate()?"":map.getStockDate()+"") ;
        }
        //创建HSSFWorkbook 艾弗森
        HSSFWorkbook wb = ExcelUtil.getHSSFWorkbook(sheetName, title, content, null);
        //响应到客户端
        try {
            this.setResponseHeader(response, fileName);
            OutputStream os = response.getOutputStream();
            wb.write(os);
            os.flush();
            os.close();
        } catch (Exception e) {
            e.printStackTrace();
        }
    }


    // 发送响应流方法
    public void setResponseHeader(HttpServletResponse response, String fileName) {
        try {
            try {
                fileName = new String(fileName.getBytes(), "ISO8859-1");
            } catch (UnsupportedEncodingException e) {
                e.printStackTrace();
            }
            response.setContentType("application/octet-stream;charset=ISO8859-1");
            response.setHeader("Content-Disposition", "attachment;filename=" + fileName);
            response.addHeader("Pargam", "no-cache");
            response.addHeader("Cache-Control", "no-cache");
        } catch (Exception ex) {
            ex.printStackTrace();
        }
    }



//    @ResponseBody
//    @RequestMapping(value = "/testProduce", method = RequestMethod.GET)
//    public void testProduce(@RequestParam("orderId")Integer orderId,
//                            HttpServletResponse response) throws IOException {
//        List<Buy> list = buyService.testProduce(orderId);
//        // 2. 设置响应头
//        response.setContentType("application/vnd.openxmlformats-officedocument.spreadsheetml.sheet");
//        response.setCharacterEncoding("utf-8");
//        String fileName = URLEncoder.encode("采购模拟订单", "UTF-8").replaceAll("\\+", "%20");
//        response.setHeader("Content-disposition", "attachment;filename*=utf-8''" + fileName + ".xlsx");
//
//        // 自定义表头顺序（按需要的顺序排列）
//        List<List<String>> customHead = new ArrayList<>();
//        customHead.add(Arrays.asList("请购单号"));
//        customHead.add(Arrays.asList("渠道"));
//        customHead.add(Arrays.asList("SKU"));
//        customHead.add(Arrays.asList("商品名称"));
//        customHead.add(Arrays.asList("颜色编码"));
//        customHead.add(Arrays.asList("颜色"));
//        customHead.add(Arrays.asList("尺码(CM)"));
//        customHead.add(Arrays.asList("尺码(INCH)"));
//        customHead.add(Arrays.asList("尺码"));
//        customHead.add(Arrays.asList("装箱量"));
//        customHead.add(Arrays.asList("请购数量"));
//        customHead.add(Arrays.asList("预计交期"));
//        customHead.add(Arrays.asList("箱数"));
//        customHead.add(Arrays.asList("货物名称"));
//        customHead.add(Arrays.asList("付款方式"));
//        customHead.add(Arrays.asList("采购单价"));
//        customHead.add(Arrays.asList("总金额"));
//        customHead.add(Arrays.asList("单位"));
//        customHead.add(Arrays.asList("供应商"));
//        // 3. 导出Excel
//        EasyExcel.write(response.getOutputStream(), Buy.class)
//                .registerWriteHandler(new LongestMatchColumnWidthStyleStrategy()) // 自动列宽
//                .excludeColumnFiledNames(Arrays.asList("id","orderId","detailId","buyDiscount","supplierName","flag","beginDate","endDate","productColorIds","productSizeIds","ids","orderNumber","orderDate","orderProductPrice","timeType","orderStatus","createTime","paymentType","productSku","productPropertyId","productPropertyName","productBigClassId","productBigClassName","productMidClassId","productMidClassName","productClassId","productClassName","productSizeId","productGrossWeight","productWeight","productContainCount","productOutBoxWeight","productOutBoxLength","productOutBoxWidth","productOutBoxHeight","productOutBoxVolume","productVolume","productLength","productWidth","productHeight","productUnit","productCode","productDeclarationName","productUpc","productDay","productFabric","productMaterial","productImg","modifyTime","createNumber","produceNumber","createWareNumber","createPortNumber","wareNumber","stockNumber"))
//                .sheet("采购订单")
//                .head(customHead)  // 设置自定义表头
//                .doWrite(convertDataToCustomOrder(list)); // 转换数据顺序
//    }
//
//
//    /**
//     * 将原始数据转换为与自定义表头匹配的顺序
//     */
//    private List<List<Object>> convertDataToCustomOrder(List<Buy> dataList) {
//        List<List<Object>> result = new ArrayList<>();
//        for (Buy buy : dataList) {
//            List<Object> row = new ArrayList<>();
//            row.add(buy.getOrderNo());
//            row.add(buy.getOrderChannelName());
//            row.add(buy.getOrderSku());
//            row.add(buy.getProductName());
//            row.add(buy.getProductColorId());
//            row.add(buy.getProductColorName());
//            row.add(buy.getProductCm());
//            row.add(buy.getProductInch());
//            row.add(buy.getProductSizeName());
//            row.add(buy.getProductPackageNumber());
//            row.add(buy.getBuyNumber());
//            row.add(buy.getBuyOrderDate());
//            row.add(buy.getBoxNumber());
//            row.add(buy.getProductClassName());
//            row.add(buy.getPaymentType());
//            row.add(buy.getProductPrice());
//            row.add(buy.getTotalPrice());
//            row.add(buy.getProductUnit());
//            row.add(buy.getSupplierName());
//            result.add(row);
//        }
//        return result;
//    }
}
